﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;

namespace CompressionEstimator
{
    public partial class ConnectionInfo : Form
    {
        #region Properties
        public SplashScreen ss;
        public int ConnectionTimeout { get; set; }
        public int ExecutionTimeout { get; set; }
        #endregion Properties

        #region Form Methods
        public ConnectionInfo()
        {
            // Standard Form code
            InitializeComponent();
            
            // make sure no items are selected
            cbAuthentication.SelectedIndex = 0;

        }
        #endregion Form Methods

        #region Event Handlers
        private void Security_CheckedChanged(object sender, EventArgs e)
        {
            // Capture current Authentication methodd
            RadioButton rb = (RadioButton)sender;
            txtUserName.Enabled = (rb.Name == "SQL Security") ? true : false;
            txtPassword.Enabled = (rb.Name == "SQL Security") ? true : false;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            // User choose not to run
            this.Close();
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            Cursor current = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;
            // Create our connection information for use by the Results Form
            SqlConnectionInfo sci = new SqlConnectionInfo(cbServer.Text);
            sci.ConnectionTimeout = ConnectionTimeout;
            bool integrated = cbAuthentication.SelectedIndex == 0 ? true : false;
            sci.UseIntegratedSecurity = integrated;
            if (!integrated)
            {
                sci.UserName = txtUserName.Text;
                sci.Password = txtPassword.Text;
            }
            
            SqlConnection con = new SqlConnection(sci.ConnectionString);
            try
            {
                // Now, make sure we can open a connection (to ensure user has rights)
                // if they don't have rights, it will throw an exception
                con.Open();
                // Work item 311
                // Check Server Version here...
                // if not 2008 or greater inform the user.
                SqlCommand cmd = new SqlCommand("SELECT SERVERPROPERTY('ProductVersion')",con);
                string verison  = (string)cmd.ExecuteScalar();
                con.Close();
                string[] verParts = verison.Split('.');
                if (Convert.ToInt32(verParts[0]) > 9)
                {
                    // Now present the main screen to the user for selection of database and processing options
                    Results r = new Results();
                    r.ConnectionInfo = sci;
                    r.ConnectionTimeout = ConnectionTimeout;
                    r.ExecutionTimeout = ExecutionTimeout;
                    r.ShowDialog();
                    this.Close();
                }
                else
                {
                    MessageBox.Show("Data Compression is only available on SQL Server 2008 or later.");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Cursor.Current = current;
            }
        }


        private void cbAuthentication_SelectedIndexChanged(object sender, EventArgs e)
        {
            // As the user changes authentication method, enable / disable the Username and Password fields 
            ComboBox cb = (ComboBox)sender;
            if (cb.SelectedIndex == 1)
            {
                txtUserName.Enabled = true;
                txtPassword.Enabled = true;
            }
            else
            {
                txtUserName.Enabled = false;
                txtPassword.Enabled = false;
            }
        }

        private void ConnectionInfo_Load(object sender, EventArgs e)
        {

        }
        #endregion Event Handlers

        private void cbServer_SelectedIndexChanged(object sender, EventArgs e)
        {
            string selection = ((ComboBox)sender).SelectedText;
            if (!string.IsNullOrEmpty(selection) && selection == "<Browse for more...>")
            {
                FillServerList();
            }
        }
        private void FillServerList()
        {
            //When the user has asked to load the server list display a message
            // and  set the location of the splash screen to our location and move it to the foreground
            // display message to user so they know why there is a delay
            ss = new SplashScreen();
            ss.Show();
            ss.Location = this.Location;
            ss.BringToFront();

            // Allow the form to display (behind the splash screen)
            this.Show();

            // Make sure the UI is repsonsive
            Application.DoEvents();

            // Save the current cursor and display a wait cursor during this operation
            Cursor current = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;

            // Use the SmoApplication to get a list of SQL Servers
            // Need to decide if this is a configuration item - only use local servers
            bool useLocalServers = false;
            DataTable dt = SmoApplication.EnumAvailableSqlServers(useLocalServers);
            cbServer.Items.Clear();
            cbServer.Items.Add("(local)");
            // Work item 311
            // Only add servers that are 2008 or greater
            foreach (DataRow r in dt.Rows)
            {
                string[] verParts = r["Version"].ToString().Split('.');
                // Only add servers that are SQL 2008 or later
                if (Convert.ToInt32(verParts[0]) > 9)
                {
                    cbServer.Items.Add(r[0].ToString());
                }
            }
            cbServer.Items.Add("<Browse for more...>");

            // Get rid of the Splash Screen
            ss.Close();

            // And restor the users cursor
            Cursor.Current = current;
        }

        private void nudConnectionTimeOut_ValueChanged(object sender, EventArgs e)
        {
            ConnectionTimeout = Convert.ToInt32(nudConnectionTimeOut.Value);
        }

        private void nudExecutionTimeout_ValueChanged(object sender, EventArgs e)
        {
            ExecutionTimeout = Convert.ToInt32(nudExecutionTimeout.Value);
        }

        private void cbServer_SelectionChangeCommitted(object sender, EventArgs e)
        {
            string selection = ((ComboBox)sender).SelectedItem.ToString();
            if (!string.IsNullOrEmpty(selection) && selection == "<Browse for more...>")
            {
                FillServerList();
            }
        }
     }
}
